// src/stores/product.js
import { defineStore } from 'pinia'
import axios from 'axios'
import { ref } from 'vue'

export const useProductStore = defineStore('product', () => {
  const stats = ref(null)

  const fetchStats = async () => {
    try {
      const res = await axios.get('/api/stats')
      if (res.data && res.data.success) {
        // 后端字段为 data
        const s = res.data.data
        stats.value = {
          totalProducts: s.totalProducts || 0,
          totalValue: s.totalValue || 0,
          totalCategories: Object.keys(s.categoryStats || {}).length,
          categoryStats: s.categoryStats || {},
          lowStockProducts: 0
        }
        return { success: true, data: stats.value }
      }
      return { success: false }
    } catch (error) {
      console.error('获取统计信息失败:', error)
      return { success: false }
    }
  }

  const fetchHotProducts = async () => {
    try {
      const res = await axios.get('/api/products/hot')
      if (res.data && res.data.success) {
        return { success: true, data: res.data.data || [] }
      }
      // 如果返回格式不对，尝试直接使用数据
      if (Array.isArray(res.data)) {
        return { success: true, data: res.data.slice(0, 4) }
      }
      return { success: false, data: [] }
    } catch (error) {
      console.error('获取热门产品失败:', error)
      return { success: false, data: [] }
    }
  }

  return {
    stats,
    fetchStats,
    fetchHotProducts
  }
})